package com.trayicon.messagenotifier.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.trayicon.messagenotifier.main.Word;

public class HttpClientUtility {
	private static HttpClientUtility THIS = null;
//	private final String DIC_SERVER = "http://localhost:8888/mainservlet";
	private final String DIC_SERVER = "http://locnvtest.appspot.com/mainservlet";
	private final String GET_DEFAULT_BOOK_CMD = "get_default_book";
	private final String ADD_WORD_CMD = "add_word";
	private final String USER_AGENT = "Mozilla/5.0";
	
	private HttpClient client = null;
	
	private HttpClientUtility() {
		client = (HttpClient)HttpClientBuilder.create().build();
	}
	
	public static HttpClientUtility getInstance() {
		if (THIS == null) {
			THIS = new HttpClientUtility();
		}
		
		return THIS;
	}
	
	private JSONParser parser = new JSONParser();
	public List<Word> getDefaultBook() {
		List<Word> lstWord = new ArrayList<Word>();
		String url = DIC_SERVER + "?cmd=" + GET_DEFAULT_BOOK_CMD;
		HttpGet request = new HttpGet(url);
		
		request.addHeader("User-Agent", USER_AGENT);
		HttpResponse response;
		String data = "";
		try {
			response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent()));

				StringBuffer result = new StringBuffer();
				String line = "";
				while ((line = rd.readLine()) != null) {
					result.append(line + "\n");
				}
				data = result.toString();
			}
			//System.out.println(result.toString());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (!data.isEmpty()) {
			try {
				JSONObject json = (JSONObject) parser.parse(data);
				JSONArray jsonArr = (JSONArray) json.get("result");
				
				Object tmp;
				for (int i = 0; i < jsonArr.size(); i++) {
					JSONObject jsonTemp = (JSONObject) jsonArr.get(i);
					Word w = new Word();
					w.setWord(jsonTemp.get("word").toString());
					tmp = jsonTemp.get("description");
					w.setMeaning(tmp != null ? tmp.toString() : "");
					
					tmp = jsonTemp.get("imagePath");
					w.setImagePath(tmp != null ? tmp.toString() : "");
					
					lstWord.add(w);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return lstWord;
	}
	
	/**
	 * add a new word into default book
	 * @param w
	 */
	public void addWord(Word w) {
		URIBuilder builder = null;
		HttpResponse response;
		try {
			builder = new URIBuilder(DIC_SERVER);
			builder.addParameter("cmd", ADD_WORD_CMD);
			builder.addParameter("word", w.getWord());
			builder.addParameter("desc", w.getMeaning());
			builder.addParameter("imgPath", w.getImagePath());
			HttpGet request = new HttpGet(builder.build());
			request.addHeader("User-Agent", USER_AGENT);
			response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				// ok, everything is good
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
	}
	
	/*public static void main(String[] args) {
		List<Word> lstWord = HttpClientUtility.getInstance().getDefaultBook();
		if (lstWord != null && !lstWord.isEmpty()) {
			for (Word w : lstWord) {
				System.out.println("- " +w.getWord());
			}
		}
	}*/
}
